/**
 * 参数详解
 * */

!function($){
    var MMPaginator = function(element, options){
        this.$el = $(element);
        this.opts = options;
    };

    MMPaginator.prototype = {
        _initLayout: function(){
            var t = this;
            var $el = this.$el;
            var opts = this.opts;

            $el.addClass("mmPaginator");
            var pgHtmls = [
                //左边
                '<div class="pageListLeft" style="'+(opts.isShowPageListLeft?'':'display:none')+'"><div class="pageLimit" style="'+(opts.isShowLimitList?'':'display:none')+'"></div></div>',
                //右边
                '<div class="pageSelectLimitWrap" style="'+(opts.isShowSelectLimit?'':'display:none')+'"><span class="pageSelectLimitTotal"></span><span>每页条数：</span><div class="pageSelectLimit"><input type="text" class="pageSelectLimit_input" value="20" readonly /><span class="pageSelectLimit_icon iconfont_dayhr_base">&#xe600;</span><ul class="pageSelectLimit_ul"></ul></div></div>'+
                '<div class="page_goto"><input class="page_goto_text" type="text" value="1"/><input class="page_goto_button" type="button" value="跳转"/></div>',
                '<div class="pageListRight">' +
                '   <ul class="pageList"></ul><li class="positionCountLabel"></li>' +
                '</div>',
            ];
            $el.append($(pgHtmls.join('')));

            this.$totalCountLabel = $el.find('.totalCountLabel');
            this.$positionCountLabel =$el.find('.positionCountLabel');
            this.$pageList = $el.find('.pageList');
            this.$limitList = $el.find('.pageLimit');
            this.$pageSelectLimitWrap = $el.find(".pageSelectLimitWrap"); //下拉选择每页条数

            $.each(opts.limitList, function(){
                var sDefaultLimit = (opts.defaultLimit && opts.defaultLimit==this)?'class="limitSelected"':'';
                var $option = $('<a href="javascript:void(0);" '+sDefaultLimit+'></a>').attr("title","每页"+this+"条").text(this); //横向按钮的
                t.$limitList.append($option);  //横向按钮的
                var $optionSelect = $('<li '+sDefaultLimit+'>'+this+'</li>'); //下拉的
                t.$pageSelectLimitWrap.find(".pageSelectLimit_ul").prepend($optionSelect); //下拉的
            });

            //横向按钮选择每页条数
            this.$limitList.on('click',"a", function(){
                $el.data('page', 1);
                $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                t.$mmGrid.load();  //重载表格数据
            });

            //跳转翻页
            $el.find(".page_goto")[opts.isShowPageGoto?"show":"hide"](); //是否显示翻页跳转
            var $text = $el.find(".page_goto_text");
            var $btngo = $el.find(".page_goto_button");
            function gotoPage(page){
                if(!/^[1-9]\d*$/.test(page)){ //必须是输入正整数
                    return false;
                }
                page = parseInt(page);
                if(page > parseInt($el.data('totalPage')) || page < 1){
                    return false;
                }
                // 跳转页
                $el.data('page', page);
                t.$mmGrid.load();
            }
            $btngo.on("click",function(){
                if($.trim($text.val())){
                    gotoPage($.trim($text.val()));
                }
            });
            $text.on("keyup",function(e){
                if(e.keyCode == 13 && $.trim($text.val())){
                    gotoPage($.trim($text.val()));
                }
            });

            //下拉选择每页条数的控件
            this.$pageSelectLimitWrap.find(".pageSelectLimit").hover(function(event){
                var _$ul = $(this).find(".pageSelectLimit_ul");
                if(_$ul.is(":hidden")){
                    _$ul.show();
                    t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").transition({ rotate: 180 },200);
                }else{
                    _$ul.hide();
                    t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").transition({ rotate: 0 },200);
                }
                event.stopPropagation();
            },function () {
                t.$pageSelectLimitWrap.find(".pageSelectLimit_ul").hide();
                t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").transition({ rotate: 0 },200);
            });
            this.$pageSelectLimitWrap.on("click","li",function(){
                $el.data('page', 1);
                $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                $(this).parent().hide();
                t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").transition({ rotate: 0 },200);
                t.$pageSelectLimitWrap.find("input.pageSelectLimit_input").val($(this).text());
                typeof opts.afterSelectLimit == "function" && opts.afterSelectLimit($(this).text()); //选择条数后的回调
                t.$mmGrid.load();  //重载表格数据
            });
            /*$(document).on("click",function(event){
                if(!$(event.target).parents(".pageSelectLimit").length){

                }
            });*/
        }

        , _plain: function(page, totalCount, limit){
            var that = this;
            var $el = this.$el;
            var $pageList = this.$pageList;
            var opts = this.opts;
            var $positionCountLabel = this.$positionCountLabel;
            var $text = $el.find(".page_goto_text");//跳转文本框
            page = parseInt(page);

            var totalPage = totalCount % limit === 0 ? parseInt(totalCount/limit) : parseInt(totalCount/limit) + 1;
            totalPage = totalPage ? totalPage : 0;
            if(totalPage === 0){
                page = 1;
            }else if(page > totalPage){
                page = totalPage;
            }else if(page < 1 && totalPage != 0){
                page = 1;
            }
            //上一页
            var $prev = $('<li class="prev"><a title="上一页">&lt;</a></li>');
            if(page<=1){
                $prev.addClass('disable');
            }else{
                $prev.find('a').on('click', function(){
                    $el.data('page', page-1);
                    $text.val("");//清空跳转文本框
                    that.$mmGrid.load();
                });
            }
            $pageList.append($prev);

            //将当前在第几页放置上一页后面
            $pageList.append($positionCountLabel);

            /////详细分页码
            if(opts.isShowPageNum){
                var list = [1];
                if(page > 4 ){
                    list.push('...');
                }
                for(var i= 0; i < 5; i++){
                    var no = page - 2 + i;
                    if(no > 1 && no <= totalPage-1){
                        list.push(no);
                    }
                }
                if(page+1 < totalPage-1){
                    list.push('...');
                }
                if(totalPage>1){
                    list.push(totalPage);
                }
                $.each(list, function(index, item){
                    var $li = $('<li><a></a></li>');
                    if(item === '...'){
                        $li.addClass('').html('...');
                    }else if(item === page){
                        $li.addClass('active').find('a').text(item);
                    }else{
                        $li.find('a').text(item).prop('title','第'+item+'页').on('click', function(e){
                            $el.data('page', item);
                            $text.val("");//清空跳转文本框
                            that.$mmGrid.load();
                        });
                    }
                    $pageList.append($li);
                });
            }

            // 下一页
            var $next = $('<li class="next"><a title="下一页">&gt;</a></li>');
            if(page>=totalPage){
                $next.addClass('disable');
            }else{
                $next.find('a').on('click', function(){
                    $el.data('page', page+1);
                    $text.val("");//清空跳转文本框
                    that.$mmGrid.load();
                });
            }
            $pageList.append($next);
        }

        , _search: function(page, totalCount, limit){

        }

        , load: function(params){
            var t = this;
            var $el = this.$el;
            var $limitList = this.$limitList;
            var opts = this.opts;

            if(!params){
                params = {pageBean:{}};
            }

            var page = params.pageBean?params.pageBean[opts.pageParamName]:undefined;
            if(page === undefined || page === null){
                page = $el.data('page');
            }
            $el.data('page', page);

            var totalCount;
            //如果参数翻页参数是两层
            if(opts.totalCountName.indexOf(".") !=-1){
                var _arr = opts.totalCountName.split(".");
                if(_arr.length==2){
                    totalCount = params[_arr[0]][_arr[1]];
                }
            }else{
                totalCount = params[opts.totalCountName];
            }
            if(totalCount === undefined){
                totalCount = 0;
            }
            $el.data('totalCount', totalCount); //总条数
            //如果总共0条记录就隐藏翻页控件，否则显示
            if(totalCount == 0){
                $el.hide();
            }else{
                $el.show();
            }

            var limit = params.pageBean?params.pageBean[opts.limitParamName]:undefined;
            if(!limit){
                if(t.opts.isShowSelectLimit){
                    limit = parseInt(this.$pageSelectLimitWrap.find("li[class='limitSelected']").text() || this.$pageSelectLimitWrap.find("li").eq(0).text()); //横向的每页条数
                }else{
                    limit = parseInt($limitList.find("a[class='limitSelected']").text() || $limitList.find("a").eq(0).text()); //横向的每页条数
                }
            }

            //选中横向当前是每页多少条
            this.$limitList.find("a").each(function(){
                if($(this).text() == limit){
                    $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                }
            });
            //选中下拉当前是每页多少条
            this.$pageSelectLimitWrap.find("li").each(function(){
                if($(this).text() == limit){
                    $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                    t.$pageSelectLimitWrap.find("input.pageSelectLimit_input").val(limit);
                }
            });

            $el.data('totalPage',Math.ceil(totalCount/limit));//总页数
            this.$totalCountLabel.html(this.formatString(opts.totalCountLabel,[totalCount])); //总记录（横向选中每页条数旁）
            this.$pageSelectLimitWrap.find(".pageSelectLimitTotal").html(this.formatString(opts.totalCountLabel,[totalCount])); //总记录（下拉选中每页条数旁）
            this.$positionCountLabel.html(this.formatString(opts.positionCountLabel,[page,$el.data('totalPage')])); //第x/x页
            this.$pageList.empty();

            if(t.opts.isShowSelectLimit){
                this._plain(page, totalCount, parseInt(this.$pageSelectLimitWrap.find("li[class='limitSelected']").text() || this.$pageSelectLimitWrap.find("li").eq(0).text())); //传送参数
            }else{
                this._plain(page, totalCount, parseInt($limitList.find("a[class='limitSelected']").text() || $limitList.find("a").eq(0).text())); //传送参数
            }
        }

        , formatString: function(text, args){
            return text.replace(/{(\d+)}/g, function(match, number) {
                return typeof args[number] != 'undefined'
                    ? args[number]
                    : match
                    ;
            });
        }
        //传参数给mmGrid
        , params: function(){
            var t = this;
            var opts = this.opts;
            var $el = this.$el;
            var $limitList = this.$limitList;

            var params = {pageBean:{}};
            params.pageBean[opts.pageParamName] = $el.data('page') +"";
            if(t.opts.isShowSelectLimit){ //下拉选择每页控件
                params.pageBean[opts.limitParamName] = parseInt(t.$pageSelectLimitWrap.find("li[class='limitSelected']").text() || t.$pageSelectLimitWrap.find("li").eq(0).text());
            }else{  //横向按钮选择每页控件
                params.pageBean[opts.limitParamName] = parseInt($limitList.find("a[class='limitSelected']").text() || $limitList.find("a").eq(0).text());
            }
            return params;  //传送这样一个数据(Object {pageBean:{page: 1, limit: "80"}})给mmGrid
        }

        , init: function($grid){
            var that = this;
            var opts = that.opts;
            this.$mmGrid = $grid;
            this._initLayout();
            this.$mmGrid.on('loadSuccess', function(e, data){
                that.load(data);
            });

            var params = {pageBean:{}};
            //如果参数翻页参数是两层json的模式
            if(opts.totalCountName.indexOf(".")!=-1){
                var _arr = opts.totalCountName.split(".");
                if(_arr.length==2){
                    params[_arr[0]] = {};
                    params[_arr[0]][_arr[1]] = 0;
                }
            }else{
                params[opts.totalCountName] = 0;
            }
            params.pageBean[opts.pageParamName] = opts.page;
            params.pageBean[opts.limitParamName] = opts.limit;
            this.load(params);

            if($grid.opts.indexCol){
                var indexCol = $grid.opts.cols[0];
                if($grid.opts.checkCol){ //如果有复选框
                    indexCol = $grid.opts.cols[1];
                }
                if($grid.opts.editButtons){ //如果有修改按钮组
                    indexCol = $grid.opts.cols[1];
                }
                if($grid.opts.checkCol && $grid.opts.editButtons){ //如果有复选框和修改按钮组
                    indexCol = $grid.opts.cols[2];
                }
                //重写序号的默认渲染函数,显示序号
                indexCol.renderer = function(val,item,rowIndex){
                    var params = that.params();
                    return '<label class="mmg-index">' +
                        (rowIndex + 1 + ((params.pageBean[opts.pageParamName]-1) * params.pageBean[opts.limitParamName])) +
                        '</label>';
                };
            }

        }

    };

    $.fn.mmPaginator = function(){

        if(arguments.length === 0 || typeof arguments[0] === 'object'){
            var option = arguments[0]
                , data = this.data('mmPaginator')
                , options = $.extend(true, {}, $.fn.mmPaginator.defaults, option);
            if (!data) {
                data = new MMPaginator(this[0], options);
                this.data('mmPaginator', data);
            }
            return $.extend(true, this, data);
        }
        if(typeof arguments[0] === 'string'){
            var data = this.data('mmPaginator');
            var fn =  data[arguments[0]];
            if(fn){
                var args = Array.prototype.slice.call(arguments);
                return fn.apply(data,args.slice(1));
            }
        }
    };

    /*默认配置*/
    $.fn.mmPaginator.defaults = {
         style: 'plain'
        , totalCountName: 'pb.pageDataCount'
        , page: 1
        , pageParamName: 'pageNo'
        , limitParamName: 'pageSize'
        , totalCountLabel: '共{0}条记录'
        , positionCountLabel: '{0}/{1}'
        , limit: undefined
        , limitList: [10, 20, 50, 100]  //每页可选多少条
        , isShowLimitList:true  //是否显示每页多少条
        , isShowSelectLimit:false //是否显示下拉每页多少条
        , defaultLimit:20
        , afterSelectLimit:undefined //选择每页条数后的回调 类型 function(iNum) 参数为先择的条数
        , isShowPageNum:false  //是否显示详细分页码
        , isShowPageListLeft:false //是否显示左侧详细分页码以及记录数
        , isShowPageGoto:false
    };

    $.fn.mmPaginator.Constructor = MMPaginator;

}(window.jQuery);
